<?php

class CreditController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;


	public function init() {

		$this->commonAction();	

	}
	//用户首页
	public function indexAction() {
		try {
		    $groupid = ( int ) $this->_request->getParam ( 'groups' );
		    $schoolid = $this->_request->getParam ( 'school' ); 		
	        $classid  = $this->_request->getParam ( 'class' ); 
			
		   $this->view->groups=$groupid; 
		   $this->view->school=$schoolid;  
		   $this->view->classid=$classid; 
		   
		   
		  // print_r($this->_user);    exit;
		 
		 if($groupid !='0' && $schoolid!='0' ){
			 
		    $where='where 1=1 ';	 
		    
			 // $groupid=$p['select1']; 
			  if($schoolid){ 
				  $schoolarray=explode('_',$schoolid);  
				  $schoolid=$schoolarray['0'];
			  } 
			 if($groupid){
				  $where .=' and  groupid="'.$groupid.'" ';
				  $this->view->groupid= $groupid; 
				 }
			 if($schoolid){
			    $where .=' and  schoolid="'.$schoolid.'" '; 
				$this->view->schoolid= $schoolid; 
			    } 
			/* if($classid){
			    $where .=' and  classid="'.$classid.'" ';
				  $this->view->classid= $classid; 
				 }*/
			  
			  
		     $count = 20;
			 $curpage = ( int ) $this->_request->getParam ( 'page' ); 
	     	if (! $curpage)
    				$curpage = 1;
			     $this->view->pageNum= $curpage;		
    			$offset = ($curpage - 1) * $count; 
			    $sql="select SQL_CALC_FOUND_ROWS *  from class_group_v ".$where."   limit $offset,$count";
			    
			    $result = $this->_dbAdapter->fetchAll ($sql);  
			     
		    	$this->view->classlist= $result;
			 
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    		//	$page->setvar ( array ('year' => $year,'week'=>$week,'foodtimeid'=>$foodtimeid) );
				$this->view->page= $page->getNumPage (); 
			    
			   }
			  
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
	 
     //处理添加操作
	 
	 public function opAction() {
		try {
	 
	   if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' ); 
				}
	   $p =$this->_request->getPost ();
	
	   // print_r($p); 
		 //		 exit;
	   //添加到credit_logs日志表中
	    if(count($p['class'])==0 ){
			throw new Exception ( '请选择班级！' ); 			
			}  
	    
	 /* if( $p['optionsRadios']==''  ){
			throw new Exception ( '请选择添加积分的类别或者请填写分数！' ); 
					
			}
		   
	   if( $p['score']=='' ){
			throw new Exception ( 'aaaaaaaaaaaaa！' ); 
			 }*/
	     
	    $a=$p['score'];
	    $b=$p['optionsRadios']; 
	    if($a!=''){
			$c=$a; 
			}
	    if($b!=''){
			$c=$b;  
			}
	    if(empty($c)){
			throw new Exception ( '请选择添加积分的类别或者请填写分数！' ); 
			} 
	    //然后再给教师增加积分
	  //查询setting 表中的time ，计算过期时间	 
	  $sql="select value from setting  where  variable='times' ";
	  $times = $this->_dbAdapter->fetchOne ($sql);
	  //查询推荐的积分
	  $sql="select value from setting  where  variable='credit_teacher_publicize' ";
	  $tjcredit= $this->_dbAdapter->fetchOne ($sql);
	  //年VIP积分
	  $sql="select value from setting  where  variable='credit_vip_year' ";
	  $yearcredit = $this->_dbAdapter->fetchOne ($sql);
	  //学期VIP积分
	  $sql="select value from setting  where  variable='credit_vip_term' ";
	  $termcredit = $this->_dbAdapter->fetchOne ($sql); 
	  $time=time();
	  $expiretime=$times+time();
	   $isok=0;  
	   $credit_logs=array(); 
	     
		 if($a!=''){
			$c=$a;
			$jifen= abs($a);
	        $credit_logs['credit_type']= 'photo';
			if($a<0){
			 $credit_logs['isminus']= '1';	
				} 
			}
	    if($b!=''){
			$c=$b; 
			 if($c=='publicize'){
				$jifen=$tjcredit; 
			   }else if($c=='year'){
				 $jifen=$yearcredit;  
			   }else if($c=='term'){
				  $jifen=$termcredit;  
			   }
		$credit_logs['credit_type']= $c;
			}
		 
	   
	   //  echo $jifen."aaaaaaaaa"; exit;
		 
		 
	   foreach($p['class'] as $key => $value){ 
	      $credit_logs['class_uid']= $value;
		  $credit_logs['credit']=$jifen;
		  $credit_logs['credit_date']=date('Y-m-d'); 
		  $credit_logs['addtime']=$time; 
		 // $credit_logs['credit_type']= $p['optionsRadios'];
		  $credit_logs['expiretime']= $expiretime; 
		  $credit_logs['ischecked']= 1; 
	  	  $res = $this->_dbAdapter->insert ('credit_logs',$credit_logs);
		  if($res){
             // $sql = 'update class set credit=credit+"'.$p['score'].'"  where uid='.$value;   
			 // $class_credit = $this->_dbAdapter->query ($sql); 
			 // if($class_credit){
				  //$isok=1;
				//发布私信
				$letter=array();
				$letter['letter_type']='txt';
				$letter['from_role']='admin';
				$letter['from_uid']='0';
				$letter['to_role']='teacher';
				$letter['to_uid']=$value;
				$letter['content']='已经成功为您增加'.$jifen.'积分。';
				$letter['addtime']=time();  
			    $letternum = $this->_dbAdapter->insert ('letter',$letter);	 
			   //发布通知
			 /* $sql="select  * from  groups where groupid='".$p['groups']."' ";
			  $groupresult = $this->_dbAdapter->fetchRow ($sql);  
		     // $noticedb=$this->getDbLink($groupname_en=$groupname);
			  
			  
			  
			    $dbArray=array();
				$dbArray['host']=$groupresult['dbhost'];
				$dbArray['username']=$groupresult['dbusername'];
				$dbArray['password']=$this->authcode($groupresult['dbpassword'], 'DECODE', 'mactop') ;
				$dbArray['dbname']=$groupresult['dbname'];
				
				$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
				Zend_Registry::set('dbAdapter', $dbAdapter);
	
				$dbAdapter=Zend_Registry::get('dbAdapter');
				$dbAdapter->query ( 'set names utf8');	 
			  
			  	 
			  $noticearray=array();	
		      $noticekey=$this->fast_uuid(); 
			  $time=time();
			  $noticearray['schoolid']=$p['schoolid'] ;
			  $noticearray['classid']=$value;
			  $noticearray['noticekey']=$noticekey;
			  $noticearray['noticetitle']='添加积分';
			  $noticearray['noticecontent']='恭喜您，获得'.$p['score'].'个积分';
			  $noticearray['addtime']=$time;
			  $noticearray['checktime']=$time;
			  $noticearray['adduserid']=$this->_user->id;
			  $noticearray['checkuserid']=$this->_user->id;	
              $noticearray['isteacher']=0;	 
			  $noticenum = $dbAdapter->insert ('notice',$noticearray);	  
			  	*/
				if($letternum){ 
					$isok=1; 
					} else{
					  $isok=0;	
				      } 
				 }else{
				  $isok=0;		 
				 }
			 // }
	     }
	   if($isok > 0){
		   
		   					//发推送
					// push_message($type,$schoolid=0,$classid=0,$uid=0,$isstudent=1,$wantsenttime=0) 
		foreach($p['class'] as $key => $value){
			$this->push_message('credit',0,0,$value,0,0);
		}

		 $this->feedback ( '添加成功', '成功', 'javascript:window.history.back();', 'tip' );   
		   }else{
		    $this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );  		   
			   } 
	 
	 } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//查询手动添加的列表
	 public function creditlistAction() {
		try {
		    
			$groupid = ( int ) $this->_request->getParam ( 'groups' );
		    $schoolid = $this->_request->getParam ( 'school' ); 		
	        $keyworld = $this->_request->getParam ( 'keyworld' ); 	
		    $this->view->groups=$groupid; 
		    $this->view->school=$schoolid;  
		if(!empty($groupid) || !empty($schoolid) ){
			$where='where  1=1';
		  if(!empty($groupid) ){
			  $where .=' and  groupid="'.$groupid.'" ';  
			 }
		   	
	      if($schoolid){
			    $where .=' and  schoolid="'.$schoolid.'" '; 
			  } 
			  
		 if($keyworld){
			    $where .=' and  classname like "%'.$keyworld.'%" '; 
			  }  
	 
	          $count = 20;
			 $curpage = ( int ) $this->_request->getParam ( 'page' ); 
	     	if (! $curpage)
    			  $curpage = 1;
			    $this->view->pageNum= $curpage;		
    			$offset = ($curpage - 1) * $count; 
			    $sql="select SQL_CALC_FOUND_ROWS *  from group_class_credit_v ".$where." and  isminus=0   limit $offset,$count";
			    //  echo $sql;  exit;
			    $result = $this->_dbAdapter->fetchAll ($sql);  
			     foreach($result as $key => $value){
				  
			 	 	 $result[$key]['password']= $this->authcode($value['password'], 'DECODE', 'mactop') ;
				 	                         
		          } 
			    
		    	$this->view->result= $result;
			 
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    		 	$page->setvar ( array ('groups' => $groupid,'school'=>$schoolid,'keyworld'=>$keyworld) );
				$this->view->page= $page->getNumPage (); 
	        
		}
		 
	
	 } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), '注意', 'javascript:window.history.back();', 'warning' );
		}
	}
	  
	//班级账号列表
	 public function classAction() {
		try { 
		    $groupid = ( int ) $this->_request->getParam ( 'groups' );
		    $schoolid = $this->_request->getParam ( 'school' ); 		
	        $classid  = $this->_request->getParam ( 'class' ); 
		    
		  $this->view->groups=$groupid; 
		  $this->view->school=$schoolid;  
		  $this->view->classid=$classid; 
		 
		    $where='where 1=1 ';	 
		    
			 // $groupid=$p['select1']; 
			  /*if($schoolid){ 
				  $schoolarray=explode('_',$schoolid);  
				  $schoolid=$schoolarray['0'];
			  } */
			 if($groupid){
				  $where .=' and  groupid="'.$groupid.'" ';
				  $this->view->groupid= $groupid; 
				 }
			 if($schoolid){
			    $where .=' and  schoolid="'.$schoolid.'" '; 
				$this->view->schoolid= $schoolid; 
			    } 
			 if($classid){
			    $where .=' and  classid="'.$classid.'" ';
				  $this->view->classid= $classid; 
				 }
			  
			  
		     $count = 20;
			 $curpage = ( int ) $this->_request->getParam ( 'page' ); 
	     	if (! $curpage)
    				$curpage = 1;
			     $this->view->pageNum= $curpage;		
    			$offset = ($curpage - 1) * $count; 
			    $sql="select SQL_CALC_FOUND_ROWS *  from class_group_v ".$where."   limit $offset,$count";
			    // echo $sql;  exit;
			    $result = $this->_dbAdapter->fetchAll ($sql);  
			     foreach($result as $key => $value){
				  
			 	  $result[$key]['password']= $this->authcode($value['password'], 'DECODE', 'mactop') ;
				                          
		       } 
			    
		    	$this->view->result= $result;
			 
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum= $param ['totalnum'];

    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    		//	$page->setvar ( array ('year' => $year,'week'=>$week,'foodtimeid'=>$foodtimeid) );
				$this->view->page= $page->getNumPage (); 
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
    
	//删除信息
      public function deleteAction() {
		try { 
         $id = ( int ) $this->_request->getParam ( 'id' );		
         $type =  $this->_request->getParam ( 'type' );	
		 $keyworld="";	
         if($type=='parents'){
			 $keyworld.="pid";
		  }else if($type=='class'){ 
			  $keyworld.="uid"; 
	      }else if($type=='student'){
			  $keyworld.="uid"; 				 
		  } 
		 
       $del_result = $this->_dbAdapter->delete ( $type, $keyworld.'='.$id);
	    
		 
	   if($del_result){ 
	      //throw new Exception ( '删除成功！' );	  
		 $this->feedback ( '删除成功', '成功', '/user/'.$type.'/', 'tip','2' );
		   }
	     
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	     


   public function groupsAction() {
		try { 
         $sql="select * from  groups ";
	     $result = $this->_dbAdapter->fetchAll ($sql);
		 for($i = 0; $i<count($result); $i++)
		{
	      $str .= "<option value='".$result[$i]['groupid']."'>".$result[$i]['groupname']."</option>";
		}
		  
	    echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//获取所有的校园列表
	  public function schoollistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		 
		  $sql="SELECT * FROM `groups` where groupid='".$p['id']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	       
/*			//连接运营库
			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		    $sql="select * from  school where groupid=".$p['id'];   
			$schoollist= $this->_dbAdapter->fetchAll ($sql);
	                 
          
			 
		 for($i = 0; $i<count($schoollist); $i++)
		{
		  $str .= "<option value='".$schoollist[$i]['schoolid']."'>".$schoollist[$i]['schoolname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	//获取所有的班级信息
	  public function classlistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		  $array=explode('_',$p['id']);
		  
		  $sql="SELECT * FROM `groups` where groupid='".$array['1']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	 
/*			//连接运营库
			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		  $sql="select * from  class  where isdel=0 and schoolid='".$array['0']."' ";   
		  $classlist= $dbAdapter->fetchAll ($sql);
	  
			 
		 for($i = 0; $i<count($classlist); $i++)
		{
		  $str .= "<option value='".$classlist[$i]['classid']."'>".$classlist[$i]['classname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
		//statistics
	public function statisticsAction(){
		try {
			$groupid = ( int ) $this->_request->getParam ( 'groupid' );
			$this->view->groupid=$groupid;
			if(!$groupid){
				$groupid='';
				$sql="SELECT * FROM `groups`";
				$result=$this->_dbAdapter ->fetchAssoc ( $sql );
				$this->view->result=$result;
			}	
			$this->view->groupid=$groupid;
			if($groupid){
				$sql="SELECT groupname FROM `groups` where groupid=".$groupid;
				$groupname=$this->_dbAdapter ->fetchOne ( $sql );
				$this->view->groupname=$groupname;
				
				$sql="select schoolid,schoolname from class where groupid='".$groupid."' and schoolname<>'' group by schoolid order by schoolid asc";
				$school=$this->_dbAdapter->fetchAssoc($sql);
				$this->view->school=$school;
			}
			
			$schoolid = ( int ) $this->_request->getParam ( 'schoolid' );
			$this->view->schoolid=$schoolid;
			if($schoolid){
				$sql="select a.*,b.classname from credit_logs_sum_v a left join class b on a.class_uid=b.uid where  a.class_uid in ( select uid from class where groupid='".$groupid."') and b.schoolid=".$schoolid;
				$statistics=$this->_dbAdapter->fetchAll($sql);
				//print_r($statistics);exit;
				$this->view->statistics=$statistics;
				
				$sql="select value from setting where variable='credits_performance'";
				$credits_performance=$this->_dbAdapter->fetchOne($sql);
				//$this->view->credits_performance=$credits_performance;
				$sql="select value from setting where variable='credit_artice_photo'";
				$credit_artice_photo=$this->_dbAdapter->fetchOne($sql);
				$this->view->credit_artice_photo=$credit_artice_photo;

				$sum_credit_photo=0;
				foreach($statistics as $key=>$value){
					$sum_credit_photo=$sum_credit_photo+$value['credit_photo']/$credit_artice_photo;
				}
				
				$this->view->performance=$sum_credit_photo*$credits_performance;
			}
			

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	public function detailedAction(){
		try {
			$class_uid = ( int ) $this->_request->getParam ( 'class_uid' );
			if (! $class_uid) {
				throw new Exception ( 'parameter_error' );
			}
			//print_r($class_uid);exit;
			$this->view->class_uid=$class_uid;
			
			if($class_uid){
				$count = 30;
				$curpage = ( int ) $this->_request->getParam ( 'page' );
				if (! $curpage)
						$curpage = 1;
					$offset = ($curpage - 1) * $count; 
				
				$sql="select SQL_CALC_FOUND_ROWS a.*,b.classname,b.schoolid,b.groupid from credit_logs a left join class b on a.class_uid=b.uid where a.ischecked=1 and a.isdelete=0 and a.class_uid='".$class_uid."' ORDER BY a.addtime desc limit $offset,$count ";
				$statistics=$this->_dbAdapter->fetchAll($sql);
				//print_r($statistics);exit;
				$this->view->statistics=$statistics;

				$param ['file'] = '/' . $this->controller . '/' . $this->action;
				$param ['totalnum'] = $this->_dbAdapter ->fetchOne ( 'SELECT FOUND_ROWS()' ); 
				$param ['perpagenum'] = $count; // 每页显示的数目
				$param ['disnum'] = 11; // 取单数显示，当前页停在中间
				$param ['curpage'] = $curpage; // 当前页码
				$this->view->allnum=$param ['totalnum'];
				$this->view->pagenum=$param ['curpage'];
				
				$page = new MyClass_Page ( $param );
				$page->setvar ( array ('class_uid' => $class_uid) );
				$this->view->page= $page->getNumPage (); 
			}
			

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}


	
	 private function fast_uuid($suffix_len=3){
        //! 计算种子数的开始时间
        static $being_timestamp = 1216681180;// 2012-5-10
       
        $time = explode(' ', microtime());
        $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6));
        if ($suffix_len > 0)
        {
            $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
        }
        return $id;
    } 
	
	 //以下内容保持不变
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method' );
	}}

